import random
import time

from gloal.mqtt import connect_mqtt

client_id = f'python-mqtt-{random.randint(0, 1000)}'
topic = f"h2s/mqtt/{random.randint(0, 1000)}"


def publish(client):
    msg_count = 0
    while True:
        time.sleep(1)
        msg = f"messages: {msg_count}"
        result = client.publish(topic, msg)
        status = result[0]
        if status == 0:
            print(f"Send `{msg}` to topic `{topic}`")
        else:
            print(f"Failed to send message to topic {topic}")
        msg_count += 1


def run():
    client = connect_mqtt(client_id)
    client.loop_start()
    publish(client)


if __name__ == '__main__':
    while True:
        run()
